/* eslint-disable */
import * as THREE from "three";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";

const mtlLoader = new MTLLoader();
const objLoader = new OBJLoader();

function loadMTL(mtlUrl) {
  return new Promise((resolve) => {
    mtlLoader.load(mtlUrl, (materials) => {
      materials.preload();
      resolve(materials);
    });
  });
}
// 加载OBJ模型
function loadOBJ(materials, objUrl) {
  return new Promise((resolve) => {
    objLoader.setMaterials(materials);
    objLoader.load(objUrl, (obj) => {
      resolve(obj);
    });
  });
}

export async function loadCar(mtlUrl, objUrl) {
  console.log(mtlUrl, objUrl);
  let materials = await loadMTL(mtlUrl);
  let carObj = await loadOBJ(materials, objUrl);
  // 调整模型的位置和方向
  carObj.rotateX(-Math.PI / 2);
  carObj.rotateZ(-Math.PI / 6);
  carObj.position.set(0, 1, 0);

  //存储模型用于判断射线相交的Mesh,car模型已经提前处理拿到所需mesh的name列表（bodyMeshName）
  let bodyMeshList = [];
  const bodyMeshName = ["bonnet", "body", "door_lf", "door_lr", "bump_front", "boot", "bump_rear", "door_rf", "door_rr"];
  carObj.children.forEach((item) => {
    if (bodyMeshName.includes(item.name)) {
      //判断存储汽车外壳对应的Mesh，用于颜色切换
      bodyMeshList.push(item);
    }
    // 有两个轮子显示有问题，修改为两面渲染
    if (item.name == "wheel01_pivot" || item.name == "wheel03_pivot") {
      item.material.forEach((mChild) => {
        mChild.side = THREE.DoubleSide;
      });
    }
  });
  return { obj: carObj, bodyMeshList: bodyMeshList, bodyColor: "debf96" };
}
export async function loadAircraft(mtlUrl, objUrl) {
  let materials = await loadMTL(mtlUrl);
  let aircraftObj = await loadOBJ(materials, objUrl);
  // 调整模型的位置和方向
  aircraftObj.rotateY(Math.PI * 0.8);
  aircraftObj.scale.set(10, 10, 10);

  let bodyMeshList = [];
  bodyMeshList.push(aircraftObj.children[0]);
  return { obj: aircraftObj, bodyMeshList: bodyMeshList, bodyColor: "5d5d5d" };
}

export async function loadNormal(mtlUrl, objUrl) {
  let materials = await loadMTL(mtlUrl);
  let normalObj = await loadOBJ(materials, objUrl);
  return { obj: normalObj };
}
